#!/usr/bin/env python
# coding: utf-8
import Lib.wxbot
import pyqrcode
import os
import thread
import time
import json
import requests
import threading
import base64
from traceback import format_exc


def run(web_input, action, bot_list):
    # action ---> http://127.0.0.1/api/*****/  其中×××对应的就是action,通过action字段来实现自定义的操作在下面主程序编写业务逻辑
    # 返回格式如下，code目前为200和500，200为正常，500为异常
    # {'code':200,'error_info':'','data':''}

    # 登陆微信机器人
    if action == 'index':
        try:
            bot_conf = json.loads(web_input['bot_conf'])
        except Exception, e:
            print '[INFO] Web WeChat load_emtry_conf -->', e
            bot_conf = {}
        robot_id = web_input['robot_id']
        type = int(web_input['type'])
        # type = 1登录, =2 重置
        if type == 1:
            try:
                i = 0
                bot_info_id = None
                for x in bot_list:
                    if x.bot_id == robot_id:
                        bot_info_id = i
                        break
                    i = i + 1
                if bot_info_id is not None:
                    if bot_list[bot_info_id].bot.my_account:
                        head_image_name = bot_list[bot_info_id].bot.get_icon(bot_list[bot_info_id].bot.my_account['UserName'])
                        with open('temp/' + head_image_name, "rb") as f:
                            head_image_base64_data = base64.b64encode(f.read())
                        data = {
                            'wx_name': bot_list[bot_info_id].bot.my_account['NickName'],
                            'wx_number': bot_list[bot_info_id].bot.my_account['Uin'],
                            'wx_signature': bot_list[bot_info_id].bot.my_account['Signature'],
                            'wx_info': bot_list[bot_info_id].bot.my_account,
                            'wx_logo': head_image_base64_data,
                            'status': 2,
                        }
                        return {'code': 200, 'error_info': '获取微信信息成功', 'data': data}
                    else:
                        return {'code': 200, 'error_info': '请扫码', 'data': {'status': 201}}
                else:
                    # 启动机器人
                    temp = weixin_bot()
                    temp.start()
                    bot_list.append(temp)

                    while 1:
                        try:
                            if temp.bot_id != '':
                                break
                            time.sleep(1)
                        except:
                            pass

                    temp.bot.bot_conf = bot_conf
                    temp.bot_start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

                    # 判断文件是否生成
                    if os.path.isfile('static/temp/' + str(temp.bot_id) + '.png'):
                        with open('static/temp/' + str(temp.bot_id) + '.png', "rb") as f:
                            # b64encode是编码，b64decode是解码
                            base64_data = base64.b64encode(f.read())
                            data = {
                                'status': 1,
                                'robot_id': str(temp.bot_id),
                                'wx_qrcode': base64_data
                            }
                            print data
                            return {'code': 200, 'error_info': '', 'data': data}
                    else:
                        return {'code': 500, 'error_info': '二维码生成失败！'}
            except Exception, e:
                print e
                return {'code': 500, 'error_info': str(e), 'data': 'try 报错'}
        else:
            data = {
                'robot_id': robot_id,
                'type': type
            }
            return {'code': 500, 'error_info': '', 'data': data}


class weixin_bot(threading.Thread):
    # 重写父类run()方法
    def run(self):
        self.bot = ReWxbot()
        self.bot.DEBUG = True
        bot_run_thread = thread.start_new_thread(self.bot.run, ())
        time.sleep(5)
        while self.bot.uuid == '':
            time.sleep(2)
            print self.bot.uuid
        self.bot_id = self.bot.uuid
        self.login_qr = '/static/temp/' + str(self.bot.uuid) + '.png'


class ReWxbot(Lib.wxbot.WXBot):

    def handle_msg_all(self, msg):
        # 载入插件系统，插件支持动态修改！修改后实时生效，无需重启程序！
        for filename in os.listdir("plugin"):
            try:
                if not filename.endswith(".py") or filename.startswith("_"):
                    continue
                pluginName = os.path.splitext(filename)[0]
                plugin = __import__("plugin." + pluginName, fromlist=[pluginName])
                reload(plugin)
                plugin.run(self, msg, pluginName)
            except Exception, e:
                print u'[ERRO] 插件%s运行错误--->%s' % (filename, e)

    def gen_qr_code(self, ts):
        string = 'https://login.weixin.qq.com/l/' + self.uuid
        qr = pyqrcode.create(string)
        qr.png(os.path.join(os.getcwd(), 'static', 'temp', str(self.uuid) + '.png'), scale=8)
